//
//  CouponViewController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/7/9.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation
class CouponViewController: UITableViewController {
    
    var pagex: Int = 1            //默认请求第一页
    var data = [User.CouponList.Coupon]()
    
    override func viewDidLoad() {
        
        view.backgroundColor = UIColor(valueRGB: 0xF9F9F9, alpha: 1.0)
        tableView.tableFooterView = UIView()
        
        let header = CustomRefreshHeader()
        tableView.gtm_addRefreshHeaderView(refreshHeader: header) { [weak self] in
            self?.requestData(isMore: true)
        }
        
        let footer = CustomRefreshFooter()
        tableView.gtm_addLoadMoreFooterView(loadMoreFooter: footer) { [weak self] in
            self?.requestData(isMore: false)
        }
        //立即刷新
        tableView.triggerRefreshing()
    }
    
    func requestData(isMore: Bool) {
        
        pagex = isMore ? 1 : pagex + 1
        JZLoading.showLoadingWith(toView: self.view)
        
        User.getUsercouponArray(page: pagex, page_size: 10, success: { [weak self] data in
            
            JZLoading.hideLoading()
            if let self = self {
                self.tableView.endRefreshing(isSuccess: true)
                
                if let data = data {
                    self.data = isMore ? data.list : self.data + data.list
                    
                    UIView.removeStatusView()
                    self.tableView.reloadData()
                    
                    if self.data.count == 0 {
                        UIView.showInfoViewWithEmpty(self.view, text: "暂无优惠券")
                        return
                    }
                }
            }
        }) { [weak self] error in
            self?.tableView.endRefreshing(isSuccess: true)
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let cell = cell as? CouponCell {
            let model = data[indexPath.row]
            cell.configItemWithInfo(model: model)
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 170
    }
}
